<?php 

namespace app\admin\controller;

class OpenLog extends Backend
{
    public function initialize()
    {
        parent::initialize();
        // 解析Token获取用户ID
        $token = request()->header("Authorization");
        $token = str_replace("Bearer ", null, $token);
        $jwt = new \Jwt();
        $this->userId = $jwt->verifyToken($token);
    }

    public function index()
    {
        $map   = [];
        $sid   = getSchooleId($this->userId);
        $map[] = ['mark', '=', 1];
        if ($sid) {
            $map[] = ['school_id', '=', $sid];
        }
        $t = getTeacher($this->userId);
        if ($t) {
            $map[] = ['class_id', 'in', getClassIds($this->userId)];
        }
        if (!empty(input('equip'))) {
            $map[] = ['equip_id', '=', input('equip')];
        }
        $data = db('openlog')
            ->where($map)
            ->field('id, ctype, student_id, create_time')
            ->order('id desc')
            ->paginate(PERPAGE, false, ['page' => PAGE]);
        $studentIds = $teacherIds = [];
        foreach ($data->items() as $val) {
            if ($val['ctype'] == 1) {
                $studentIds[] = $val['student_id'];
            } else {
                $teacherIds[] = $val['student_id'];
            }
        }
        $students = db('student')->whereIn('id', $studentIds)->field('id_card,name,id')->select();
        $students = array_column($students, null, 'id');
        $teachers = db('user')->whereIn('id', $teacherIds)->field('mobile,realname,id')->select();
        $teachers = array_column($teachers, null, 'id');
        $data->each(function ($val) use ($students, $teachers) {
            if ($val['ctype'] == 1) {
                $val['name'] = $students[$val['student_id']]['name'] ?? '';
                $val['code'] = $students[$val['student_id']]['id_card'] ?? '';
            } else {
                $val['name'] = $teachers[$val['student_id']]['realname'] ?? '';
                $val['code'] = $teachers[$val['student_id']]['mobile'] ?? '';
            }
            return $val;
        });

        return $this->jsonReturn(
            [
                'msg'   => '操作成功',
                'code'  => 0,
                'data'  => $data->items(),
                'count' => $data->total()
            ]
        );
    }
                                                    
}